<template>
  <div class="model-manage-container">
    <div class="page-header">
      <h2 class="page-title">模型管理</h2>
      <a-button type="primary" @click="showCreateModal">
        <plus-outlined /> 创建模型
      </a-button>
    </div>

    <div class="model-list">
      <a-row :gutter="[16, 16]">
        <a-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8" v-for="model in modelList" :key="model.id">
          <a-card class="model-card">
            <div class="model-card-header">
              <div class="model-icon">
                <img :src="getModelIcon(model.provider)" :alt="model.name" />
              </div>
              <div class="model-name">{{ model.name }}</div>
              <a-dropdown placement="bottomRight">
                <a-button type="text" class="more-button">
                  <ellipsis-outlined />
                </a-button>
                <template #overlay>
                  <a-menu>
                    <a-menu-item key="edit" @click="editModel(model)">
                      <edit-outlined /> 编辑
                    </a-menu-item>
                    <a-menu-item key="delete" @click="confirmDelete(model)">
                      <delete-outlined /> 删除
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </div>

            <div class="model-info">
              <div class="info-item">
                <span class="label">提供商:</span>
                <span class="value">{{ getProviderName(model.provider) }}</span>
              </div>
              <div class="info-item">
                <span class="label">Host:</span>
                <span class="value">{{ model.host }}</span>
              </div>
              <div class="info-item">
                <span class="label">Manage Host:</span>
                <span class="value">{{ model.manageHost }}</span>
              </div>
              <div class="info-item">
                <span class="label">Last Heart Beat:</span>
                <span class="value">{{ model.lastHeartBeat }}</span>
              </div>
            </div>

            <div class="model-tags">
              <a-tag color="green" v-if="model.status === 'Healthy'">Healthy</a-tag>
              <a-tag v-else>{{ model.status }}</a-tag>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 创建/编辑模型对话框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="800px"
    >
      <a-form :model="formState" :rules="rules" ref="formRef" layout="vertical">
        <a-form-item label="模型名称" name="name">
          <a-input v-model:value="formState.name" placeholder="请输入模型名称" />
        </a-form-item>
        
        <a-form-item label="模型提供商" name="provider">
          <model-provider-selector v-model="formState.provider" @select="handleProviderSelect" />
        </a-form-item>
        
        <a-form-item label="Host" name="host">
          <a-input v-model:value="formState.host" placeholder="请输入Host地址" />
        </a-form-item>
        
        <a-form-item label="Manage Host" name="manageHost">
          <a-input v-model:value="formState.manageHost" placeholder="请输入Manage Host地址" />
        </a-form-item>
        
        <a-form-item label="状态" name="status">
          <a-select v-model:value="formState.status">
            <a-select-option value="Healthy">Healthy</a-select-option>
            <a-select-option value="llm">llm</a-select-option>
            <a-select-option value="text2vec">text2vec</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 删除确认对话框 -->
    <a-modal
      v-model:visible="deleteModalVisible"
      title="确认删除"
      @ok="handleDeleteOk"
      @cancel="handleDeleteCancel"
      okText="确认"
      cancelText="取消"
    >
      <p>确定要删除模型 "{{ currentModel?.name }}" 吗？</p>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { message } from 'ant-design-vue';
import { 
  PlusOutlined,
  EllipsisOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue';
import type { ModelItem } from '../types/model';
import ModelProviderSelector from '../components/ModelProviderSelector.vue';

// 引入所有模型图标
import openaiIcon from '../assets/icons/model/openai.png';
import anthropicIcon from '../assets/icons/model/anthropic.png';
import claudeIcon from '../assets/icons/model/claude.png';
import mistralIcon from '../assets/icons/model/mistral.png';
import geminiIcon from '../assets/icons/model/gemini.png';
import metaIcon from '../assets/icons/model/meta.png';
import chatglmIcon from '../assets/icons/model/chatglm.png';
import gemmaIcon from '../assets/icons/model/gemma.png';
import qwenIcon from '../assets/icons/model/qwen.png';
import doubaoIcon from '../assets/icons/model/doubao.png';
import baiducloudIcon from '../assets/icons/model/baiducloud.png';
import deepseekIcon from '../assets/icons/model/deepseek.png';
import hunyuanIcon from '../assets/icons/model/hunyuan.png';
import modelscopeIcon from '../assets/icons/model/modelscope.png';
import sparkIcon from '../assets/icons/model/spark.png';
import tiangongIcon from '../assets/icons/model/tiangong.png';
import volcengineIcon from '../assets/icons/model/volcengine.png';
import baichuanIcon from '../assets/icons/model/baichuan.png';
import siliconcloudIcon from '../assets/icons/model/siliconcloud.png';
import moonshotIcon from '../assets/icons/model/moonshot.png';

// 图标映射
const modelIcons = {
  openai: openaiIcon,
  anthropic: anthropicIcon,
  claude: claudeIcon,
  mistral: mistralIcon,
  gemini: geminiIcon,
  meta: metaIcon,
  chatglm: chatglmIcon,
  gemma: gemmaIcon,
  qwen: qwenIcon,
  doubao: doubaoIcon,
  baiducloud: baiducloudIcon,
  deepseek: deepseekIcon,
  hunyuan: hunyuanIcon,
  modelscope: modelscopeIcon,
  spark: sparkIcon,
  tiangong: tiangongIcon,
  volcengine: volcengineIcon,
  baichuan: baichuanIcon,
  siliconcloud: siliconcloudIcon,
  moonshot: moonshotIcon
};

// 提供商名称映射
const providerNames = {
  openai: 'OpenAI',
  anthropic: 'Anthropic',
  claude: 'Claude',
  mistral: 'Mistral',
  gemini: 'Gemini',
  meta: 'Meta',
  chatglm: 'ChatGLM',
  gemma: 'Gemma',
  qwen: 'Qwen',
  doubao: '豆包',
  baiducloud: '百度智能云',
  deepseek: 'DeepSeek',
  hunyuan: '混元',
  modelscope: 'ModelScope',
  spark: '讯飞星火',
  tiangong: '天工',
  volcengine: '火山引擎',
  baichuan: '百川',
  siliconcloud: 'Silicon Cloud',
  moonshot: 'Moonshot'
};

// 获取模型图标
const getModelIcon = (provider: string) => {
  return modelIcons[provider as keyof typeof modelIcons] || '';
};

// 获取提供商名称
const getProviderName = (provider: string) => {
  return providerNames[provider as keyof typeof providerNames] || provider;
};

// 模型列表
const modelList = ref<ModelItem[]>([]);

// 表单相关
const formRef = ref();
const modalVisible = ref(false);
const modalTitle = ref('创建模型');
const isEdit = ref(false);
const currentModel = ref<ModelItem | null>(null);

// 删除相关
const deleteModalVisible = ref(false);

// 表单状态
const formState = reactive({
  id: '',
  name: '',
  provider: 'openai',
  host: '',
  manageHost: '',
  status: 'Healthy',
  lastHeartBeat: ''
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入模型名称', trigger: 'blur' }],
  provider: [{ required: true, message: '请选择模型提供商', trigger: 'change' }],
  host: [{ required: true, message: '请输入Host地址', trigger: 'blur' }],
  manageHost: [{ required: true, message: '请输入Manage Host地址', trigger: 'blur' }]
};

// 处理提供商选择
const handleProviderSelect = (provider: any) => {
  // 可以根据选择的提供商预填充一些默认值
  if (provider.id === 'openai') {
    formState.host = 'https://api.openai.com/v1/chat/completions';
    formState.manageHost = 'https://platform.openai.com';
  } else if (provider.id === 'anthropic' || provider.id === 'claude') {
    formState.host = 'https://api.anthropic.com/v1/messages';
    formState.manageHost = 'https://console.anthropic.com';
  }
};

// Mock数据生成
const generateMockModelList = () => {
  return [
    {
      id: '1',
      name: 'GPT-3.5',
      provider: 'openai',
      host: 'https://api.openai.com/v1/chat/completions',
      manageHost: 'https://platform.openai.com',
      status: 'Healthy',
      lastHeartBeat: '2023-10-18 12:30:45',
      createdAt: '2023-10-01',
      updatedAt: '2023-10-01'
    },
    {
      id: '2',
      name: 'GPT-4',
      provider: 'openai',
      host: 'https://api.openai.com/v1/chat/completions',
      manageHost: 'https://platform.openai.com',
      status: 'Healthy',
      lastHeartBeat: '2023-10-18 12:35:22',
      createdAt: '2023-10-02',
      updatedAt: '2023-10-02'
    },
    {
      id: '3',
      name: 'Claude-2',
      provider: 'claude',
      host: 'https://api.anthropic.com/v1/messages',
      manageHost: 'https://console.anthropic.com',
      status: 'llm',
      lastHeartBeat: '2023-10-18 12:28:11',
      createdAt: '2023-10-03',
      updatedAt: '2023-10-03'
    },
    {
      id: '4',
      name: 'Embedding-Model',
      provider: 'mistral',
      host: 'https://api.embedding.com/v1',
      manageHost: 'https://console.embedding.com',
      status: 'text2vec',
      lastHeartBeat: '2023-10-18 12:40:33',
      createdAt: '2023-10-04',
      updatedAt: '2023-10-04'
    }
  ] as ModelItem[];
};

// 获取模型列表 - 使用Mock数据
const fetchModelList = () => {
  // 模拟网络请求延迟
  setTimeout(() => {
    modelList.value = generateMockModelList();
  }, 300);
};

// 显示创建模型对话框
const showCreateModal = () => {
  modalTitle.value = '创建模型';
  isEdit.value = false;
  resetForm();
  modalVisible.value = true;
};

// 编辑模型
const editModel = (model: ModelItem) => {
  modalTitle.value = '编辑模型';
  isEdit.value = true;
  currentModel.value = model;
  
  // 填充表单数据
  Object.keys(formState).forEach(key => {
    (formState as any)[key] = model[key as keyof ModelItem];
  });
  
  modalVisible.value = true;
};

// 确认删除
const confirmDelete = (model: ModelItem) => {
  currentModel.value = model;
  deleteModalVisible.value = true;
};

// 处理模态框确认
const handleModalOk = () => {
  formRef.value.validate().then(() => {
    if (isEdit.value) {
      // 模拟更新模型
      const index = modelList.value.findIndex(item => item.id === currentModel.value?.id);
      if (index !== -1) {
        modelList.value[index] = {
          ...modelList.value[index],
          name: formState.name,
          provider: formState.provider,
          host: formState.host,
          manageHost: formState.manageHost,
          status: formState.status,
          updatedAt: new Date().toISOString().split('T')[0]
        };
        message.success('更新模型成功');
      }
    } else {
      // 模拟创建模型
      const newModel: ModelItem = {
        id: Math.random().toString(36).substring(2, 11),
        name: formState.name,
        provider: formState.provider,
        host: formState.host,
        manageHost: formState.manageHost,
        status: formState.status,
        lastHeartBeat: new Date().toLocaleString(),
        createdAt: new Date().toISOString().split('T')[0],
        updatedAt: new Date().toISOString().split('T')[0]
      };
      
      modelList.value.unshift(newModel);
      message.success('创建模型成功');
    }
    
    modalVisible.value = false;
    resetForm();
  }).catch((error: any) => {
    console.log('验证失败', error);
  });
};

// 取消模态框
const handleModalCancel = () => {
  modalVisible.value = false;
  resetForm();
};

// 处理删除确认
const handleDeleteOk = () => {
  if (!currentModel.value) return;
  
  // 模拟删除操作
  modelList.value = modelList.value.filter(item => item.id !== currentModel.value?.id);
  message.success('删除模型成功');
  deleteModalVisible.value = false;
  currentModel.value = null;
};

// 取消删除
const handleDeleteCancel = () => {
  deleteModalVisible.value = false;
  currentModel.value = null;
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  
  // 手动重置一些可能不在表单验证中的字段
  formState.id = '';
  formState.provider = 'openai';
  formState.lastHeartBeat = '';
};

onMounted(() => {
  fetchModelList();
});
</script>

<style scoped>
.model-manage-container {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.model-list {
  margin-top: 16px;
}

.model-card {
  height: 100%;
  transition: all 0.3s;
  border-radius: 8px;
}

.model-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.model-card-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.model-icon {
  width: 64px;
  height: 64px;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  margin-right: 16px;
}

.model-icon img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.model-name {
  flex: 1;
  font-weight: 500;
  font-size: 16px;
  color: #333;
}

.more-button {
  color: #999;
}

.model-info {
  margin: 16px 0;
}

.info-item {
  display: flex;
  margin-bottom: 12px;
  text-align: left;
}

.label {
  color: #666;
  width: 120px;
  text-align: left;
}

.value {
  color: #333;
  flex: 1;
  text-align: left;
}

.model-tags {
  margin-top: 12px;
}
</style> 